//
//  GooglePassWordView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/5/31.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
class GooglePassWordView: UIView {
    var delegate:GoolPassWordDelegate?
    var passWord:String = "" //密码
    var code:String = ""  //验证码
    
    lazy var selectBtn:UIButton = {
        let btn =  CommonBtn.creatSelectBtnWithTitle(title: kText("确认"), y: 36, view: self, sel:  #selector(selectBtnAction))
        return btn
    }()

    var style:googleStyle?
    var validate:validateStyle?
    lazy var verificationView:UIView = {
        let view = UIView()
        view.themeBackground = ThemeManager.ThemeColorKeys.background
        return view
    }()
    lazy var timerBtn:TimerBtn = {
        let btn = TimerBtn()
        btn .addTarget(self, action: #selector(getSMSCode(button:)), for: UIControlEvents.touchUpInside)
        return btn
    }()
  
    lazy var passWordTextField: UITextField = {
        let textField = UITextField()
        textField.delegate  = self
        textField.font = UIFont.systemFont(ofSize: 13)
        textField.keyboardType = .numberPad
        textField.inputAccessoryView = self.generateToolbar()
        textField.themeTextColor  = ThemeManager.ThemeColorKeys.text1
        return textField
    }()
    lazy var codeTextField: UITextField = {
        let textField = UITextField()
        textField.delegate = self
        textField.font = UIFont.systemFont(ofSize: 13)
        textField.inputAccessoryView = self.generateToolbar()
        textField.keyboardType = .numberPad
        textField.themeTextColor  = ThemeManager.ThemeColorKeys.text1
        return textField
    }()
    init(dataSource:GoolPassWordDelegate?, style:googleStyle,validate:validateStyle) {
        super.init(frame:CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: kSCREEN_HEIGHT))
        self.validate = validate
        self.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        delegate = dataSource
        self.style = style
        NotificationCenter.default.addObserver(self, selector: #selector(notifierKeyboardWillShow), name:NSNotification.Name.UIKeyboardWillShow, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(notifierKeyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        
    }
    func generateToolbar() -> UIToolbar {
        let toolbar =  UIToolbar(frame: CGRect(x: 0.0, y: 0.0, width: kSCREEN_WIDTH, height: 44.0))
        let itme1 = UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.flexibleSpace , target: nil, action: nil)
        let item2 = UIBarButtonItem(title: kText("完成"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(doneButtonDidPressed))
        toolbar.setItems([itme1, item2], animated: false)
        return toolbar
    }
    
    @objc func doneButtonDidPressed() -> Void {
        self.endEditing(true)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
   open func setUpUI() {
    let ipxHeight = isiPhoneX() ? 34 : 0
    UIApplication.shared.keyWindow?.addSubview(self)
    self.snp.makeConstraints { (make) in
        make.left.top.right.equalToSuperview()
        make.bottom.equalToSuperview().offset(-ipxHeight)
    }
        self.addSubview(verificationView)
        
        let titleLabel = BaseLabel(style: .oneStyle)
        titleLabel.font = UIFont.systemFont(ofSize: 15)
        titleLabel.text = kText("安全验证")
//        titleLabel.textColor = kTitleColor
        verificationView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(25)
        }
        
        let closeBtn = UIButton()
        closeBtn.setImage(UIImage(named: "closePop"), for: UIControlState.normal)
        closeBtn.addTarget(self, action: #selector(closeAction), for: UIControlEvents.touchUpInside)
        verificationView.addSubview(closeBtn)
        closeBtn.snp.makeConstraints { (make) in
            make.right.equalToSuperview()
            make.top.equalToSuperview()
            make.width.equalTo(36)
            make.height.equalTo(36)
        }
    
        let nameLabel = BaseLabel(style:.twiceStyle)
        nameLabel.font = UIFont.systemFont(ofSize: 13)
        nameLabel.text = kText("支付密码")
        verificationView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { (make) in
        make.left.equalToSuperview().offset(15)
        make.top.equalToSuperview().offset(62)
        }
    
    
    verificationView.addSubview(passWordTextField)

    passWordTextField.placeholder = kText("输入6位支付密码")
    if ThemeManager.default.currentThemeMode() == .night {
        passWordTextField.setValue(UIColor(hexStr: "#616979"), forKeyPath: "_placeholderLabel.textColor")
    }else {
        passWordTextField.setValue(UIColor(hexStr: "#b1b2b2"), forKeyPath: "_placeholderLabel.textColor")
    }
    passWordTextField.snp.makeConstraints { (make) in
        make.top.equalToSuperview().offset(94)
        make.left.equalToSuperview().offset(15)
        make.right.equalToSuperview().offset(-15)
        make.height.equalTo(20)
    }
    
    let forgotPassWordBtn = UIButton()
    forgotPassWordBtn.isHidden = true
    forgotPassWordBtn.addTarget(self, action: #selector(forgotPassWordBtnAction), for: UIControlEvents.touchUpInside)
    forgotPassWordBtn.setTitle(kText("忘记支付密码"), for: UIControlState.normal)
    forgotPassWordBtn.setTitleColor(kThemeColor, for: UIControlState.normal)
    forgotPassWordBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
    verificationView.addSubview(forgotPassWordBtn)
    forgotPassWordBtn.snp.makeConstraints { (make) in
        make.right.equalToSuperview().offset(-15)
        make.top.equalTo(passWordTextField.snp.bottom).offset(15)
    }
    
    
    let line:UIView = UIView()
    line.themeBackground = ThemeManager.ThemeColorKeys.tabLineColor
    verificationView.addSubview(line)
    line.snp.makeConstraints { (make) in
        make.left.equalToSuperview().offset(15)
        make.right.equalToSuperview().offset(-15)
        make.top.equalToSuperview().offset(124)
        make.height.equalTo(0.5)
    }
    
    
    let vertyLabel = BaseLabel(style:.twiceStyle)
    vertyLabel.font = UIFont.systemFont(ofSize: 13)
    vertyLabel.text = kText("短信验证")
    verificationView.addSubview(vertyLabel)
    vertyLabel.snp.makeConstraints { (make) in
        make.left.equalToSuperview().offset(15)
        make.top.equalToSuperview().offset(155)
    }
    
    verificationView.addSubview(codeTextField)
    codeTextField.placeholder = kText("输入短信验证码")
    if ThemeManager.default.currentThemeMode() == .night {
        codeTextField.setValue(UIColor(hexStr: "#616979"), forKeyPath: "_placeholderLabel.textColor")
    }else {
        codeTextField.setValue(UIColor(hexStr: "#b1b2b2"), forKeyPath: "_placeholderLabel.textColor")
    }
    codeTextField.snp.makeConstraints { (make) in
        make.top.equalToSuperview().offset(187)
        make.left.equalToSuperview().offset(15)
        make.right.equalToSuperview().offset(-15)
        make.height.equalTo(20)
    }
    

    let botLine:UIView = UIView()
    botLine.themeBackground = ThemeManager.ThemeColorKeys.tabLineColor
    verificationView.addSubview(botLine)
    botLine.snp.makeConstraints { (make) in
        make.left.equalToSuperview().offset(15)
        make.right.equalToSuperview().offset(-15)
        make.top.equalToSuperview().offset(217)
        make.height.equalTo(0.5)
    }
    
    selectBtn.isEnabled = false
    CommonBtn.createImageWithColor(color: kDisableColor, btn: selectBtn, state: UIControlState.normal)
    verificationView.addSubview(selectBtn)
    selectBtn.snp.makeConstraints { (make) in
        make.bottom.equalToSuperview().offset(-15)
        make.height.equalTo(40)
        make.left.equalToSuperview().offset(15)
        make.right.equalToSuperview().offset(-15)
    }
    
    
    if style == googleStyle.googlePassWordStyle{
        if self.validate == .telStyle || self.validate == .emailStyle {
            verificationView.addSubview(timerBtn)
            timerBtn.snp.makeConstraints { (make) in
                make.centerY.equalTo(passWordTextField)
                make.height.equalTo(42)
                make.right.equalToSuperview().offset(-5)
                make.width.equalTo(145)
            }
            passWordTextField.snp.updateConstraints { (make) in
                make.right.equalToSuperview().offset(-180)
            }
        timerBtn.isHidden = false
        }else {
            timerBtn.isHidden = true
        }
            codeTextField.isHidden = true
            botLine.isHidden = true
            vertyLabel.isHidden = true
            verificationView.snp.makeConstraints { (make) in
                make.bottom.equalToSuperview()
                make.left.right.equalToSuperview()
                make.height.equalTo(225)
            }
            switch self.validate {
            case .none?:
                nameLabel.text = kText("支付密码")
                passWordTextField.placeholder = kText("输入6位支付密码")
                forgotPassWordBtn.isHidden = false
                passWordTextField.isSecureTextEntry = true
                break
            case .telStyle?:
                nameLabel.text = kText("手机验证码")
                passWordTextField.placeholder = kText("输入手机验证码")
                break
                
            case .googleStyle?:
                nameLabel.text = kText("谷歌验证码")
                passWordTextField.placeholder = kText("输入6位谷歌验证码")
                break
            case .emailStyle?:
                nameLabel.text = kText("邮箱验证码")
                passWordTextField.placeholder = kText("输入6位邮箱验证码")
                break
                
            default: break
        }
        }else if style ==  .googleDoubleAuthen{
            passWordTextField.isSecureTextEntry = true
            forgotPassWordBtn.isHidden = false
            verificationView.snp.makeConstraints { (make) in
                make.bottom.equalToSuperview()
                make.left.right.equalToSuperview()
                make.height.equalTo(310)
            }
        if self.validate == .telStyle || self.validate == .emailStyle {
            verificationView.addSubview(timerBtn)
            timerBtn.snp.makeConstraints { (make) in
                make.centerY.equalTo(codeTextField)
                make.height.equalTo(42)
                make.right.equalToSuperview().offset(-5)
                make.width.equalTo(145)
            }
            codeTextField.snp.updateConstraints { (make) in
                make.right.equalToSuperview().offset(-180)
            }
            timerBtn.isHidden = false
        }else {
            timerBtn.isHidden = true
        }
        switch self.validate {
        case .none?:
            vertyLabel.text = kText("支付密码")
            codeTextField.placeholder = kText("输入6位支付密码")
            forgotPassWordBtn.isHidden = false
            codeTextField.isSecureTextEntry = true
            break
        case .telStyle?:
            vertyLabel.text = kText("手机验证码")
            codeTextField.placeholder = kText("输入手机验证码")
            break
            
        case .googleStyle?:
            vertyLabel.text = kText("谷歌验证码")
            codeTextField.placeholder = kText("输入6位谷歌验证码")
            break
        case .emailStyle?:
            vertyLabel.text = kText("邮箱验证码")
            codeTextField.placeholder = kText("输入6位邮箱验证码")
            break
            
           default: break
        
        }
        
       }
    }
    
    @objc func closeAction() {
        
        if self.delegate != nil && self.delegate?.cancel != nil {
            self.delegate?.cancel!()
//            self.delegate?.googleVerificationt(passWord: "")
        }
        timerBtn.invlidateTimer()
        self.removeFromSuperview()
    }
    
    @objc func getSMSCode(button:TimerBtn) {
        if AppSecurityInfo.default.model.isMobileBind {
            button.isEnabled = false
            AppSecurityInfo.default.archiveMobileCode(success: { (result) in
                button.timeStart()
            }) { (response) in
                if Helper.checkTimerCode(response:response.response) {
                    button.timeStart()
                }else {
                    button.isEnabled = true
                }
            }
        }
    }
    
    @objc func selectBtnAction() {
        if self.validate == nil {
            CYMBShow.showMessage(kText("系统异常,请稍后重试"))
            return
        }
        if style == .googlePassWordStyle {
        if passWord.count < 6 {
            if self.validate! == .none {
                CYMBShow.showMessage(kText("请输入6位支付密码"))
            }else if self.validate! == .telStyle {
                CYMBShow.showMessage(kText("请输入手机短信验证码"))
            }else if self.validate! == .emailStyle {
                CYMBShow.showMessage(kText("请输入邮箱验证码"))
            }else if self.validate! == .googleStyle {
                CYMBShow.showMessage(kText("请输入谷歌验证码"))
            }
            return
        }
        }else if style == .googleDoubleAuthen {
            if passWord.count < 6 {
                CYMBShow.showMessage(kText("请输入6位支付密码"))
                return
            }
            if code.count < 6 {
                if self.validate! == .none {
                    CYMBShow.showMessage(kText("请输入6位支付密码"))
                }else if self.validate! == .telStyle {
                    CYMBShow.showMessage(kText("请输入手机短信验证码"))
                }else if self.validate! == .emailStyle {
                    CYMBShow.showMessage(kText("请输入邮箱验证码"))
                }else if self.validate! == .googleStyle {
                    CYMBShow.showMessage(kText("请输入谷歌验证码"))
                }
                return
            }
        }
            
            
            
        if self.delegate != nil && self.delegate?.googleVerificationt != nil {
            if style == .googlePassWordStyle  {
            self.delegate?.googleVerificationt(passWord: passWord)
            }else {
               self.delegate?.googleVerificationt(passWord: passWord + "/" + code)
            }
        }
        timerBtn.invlidateTimer()
        self.removeFromSuperview()
    }
    
    func changeStates()  {
        var isSuccess:Bool = true
        if style == .googleDoubleAuthen {
            if code.ch_length == 0 {
                isSuccess = false
            }
        }
    
    if passWord.ch_length != 0 && isSuccess {
        selectBtn.isEnabled = true
        CommonBtn.createImageWithColor(color:kThemeColor, btn: selectBtn, state: UIControlState.normal)
    }else {
        selectBtn.isEnabled = false
            CommonBtn.createImageWithColor(color: kDisableColor, btn: selectBtn, state: UIControlState.normal)
        }
    }
    
    @objc func forgotPassWordBtnAction() {
        timerBtn.invlidateTimer()
        self.removeFromSuperview()
        let controller = CYMBShow.currentController()
        let passWordController = SetPassWordViewController()
        controller?.navigationController?.pushViewController(passWordController, animated: true)
        
    }
    
    
    @objc func notifierKeyboardWillShow(notification:NSNotification) {
        let userInfo = notification.userInfo as NSDictionary?
        
        let aValue = userInfo?.object(forKey: UIKeyboardFrameEndUserInfoKey)
        
        let keyboardSize = (aValue as AnyObject).cgRectValue
        
        let animationDuration =  (userInfo?.object(forKey: UIKeyboardAnimationDurationUserInfoKey) as! NSNumber).doubleValue
        
        let animationCurve = (userInfo?.object(forKey: UIKeyboardAnimationCurveUserInfoKey) as! NSNumber).intValue
        
        let height = -((keyboardSize?.size.height)! - (isiPhoneX() ? CGFloat(34) : CGFloat(0)))
        
        UIView.animateKeyframes(withDuration: animationDuration, delay: 0, options: UIViewKeyframeAnimationOptions(rawValue: UIViewKeyframeAnimationOptions.RawValue(animationCurve)), animations: {
            self.verificationView.snp.updateConstraints({ (make) in
                make.bottom.equalToSuperview().offset(height)
            })
            self.layoutIfNeeded()
            
        }) { (make) in
            
        }
    }
    
    
    @objc func notifierKeyboardWillHide(notification:NSNotification) {
        let userInfo = notification.userInfo as NSDictionary?
        let animationDuration =  (userInfo?.object(forKey: UIKeyboardAnimationDurationUserInfoKey) as! NSNumber).doubleValue
        
        let animationCurve = (userInfo?.object(forKey: UIKeyboardAnimationCurveUserInfoKey) as! NSNumber).intValue
        
        UIView.animateKeyframes(withDuration: animationDuration, delay: 0, options: UIViewKeyframeAnimationOptions(rawValue: UIViewKeyframeAnimationOptions.RawValue(animationCurve)), animations: {
            self.verificationView.snp.updateConstraints({ (make) in
                make.bottom.equalToSuperview().offset(0)
            })
            self.layoutIfNeeded()
        }) { (make) in
            
        }
        
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
extension GooglePassWordView:UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
                   replacementString string: String) -> Bool {
         let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        if newString.ch_length > 6 {
            return false
        }
        if textField.isEqual(passWordTextField) {
           passWord = newString
        }else {
            code = newString
        }
        self.changeStates()
        return true
    }
    
    
}
